/**
 * @description render elem
 * @author wangfupeng
 */

import { h, VNode } from 'snabbdom';
import { DomEditor, IDomEditor, SlateElement } from '@wangeditor/editor';
import { MentionElement } from '../custom-types';

function renderMention(elem: SlateElement, children: VNode[] | null, editor: IDomEditor): VNode {
  // 当前节点是否选中
  const selected = DomEditor.isNodeSelected(editor, elem);
  const { value = '', info = {}, url = '', typeLink = '', target = '' } = elem as MentionElement;
  const infoStr = encodeURIComponent(JSON.stringify(info));
  // 构建 vnode
  const vnode = h(
    'a',
    {
      props: {
        contentEditable: false, // 不可编辑
        href: url,
        infoStr,
        value,
        typeLink,
        target,
        className: 'w-e-textarea-mention',
      },
      style: {
        border: selected // 选中/不选中，样式不一样
          ? '2px solid var(--w-e-textarea-selected-border-color)' // wangEditor 提供了 css var https://www.wangeditor.com/v5/theme.html
          : '2px solid transparent',
      },
      on: {
        mousedown: (event) => event.preventDefault(),// 阻止默认行为
        click: (event) => { // 添加 click 事件处理器
          event.preventDefault(); // 阻止默认行为
        },
      }, 
    },
    `${value}`, // 如 `@张三`
  );

  return vnode;
}

const conf = {
  type: 'mention', // 节点 type ，重要！！！
  renderElem: renderMention,
};

export default conf;
